
"use client"

import { useEffect, useState } from "react";
import { InsertDialog, ItemDialog } from "../../dialog/dialog";

export default () => {

  const [showDialog, setShowDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [data, setData] = useState<Item>();
  const [items, setItems] = useState<Item[]>();

  const handleItemExitClick = (name: string | null) => {
    setShowDetailDialog(true);

    const item = items?.find((item) => item.name == name);
    setData(item);
  };

  const handleExitClick = () => {
    setShowDialog(true);
  };

  useEffect(() => {

    const fetchUrl = async () => {
        const res = await (await fetch('/api/list')).json();
        setItems(JSON.parse(res));
    }

    fetchUrl();
}, []);

  return (
    <>
      <div>
        <button style={{
          backgroundColor: '#00BCD4', borderRadius: '5px', padding: '2px 20px', border: '2px solid black',
          cursor: 'pointer', outline: 'none', marginTop: '15px', marginLeft: '1200px'
        }} onClick={handleExitClick}>
          添加项目
        </button>
      </div>

      <hr style={{ marginTop: '20px' }} />

      {items?.map((item) => (
        <div>
          <button style={{
            display: 'inline-block',
            padding: '0px 70px 4px',
            margin: '10px 10px 0',
            backgroundColor: 'red',
            border: '1px solid #000',
            borderRadius: '5px', 
            width: '150px'
          }} 
          onClick={() => handleItemExitClick(item.name)}>
            {item.name}
            </button>
        </div>
      ))}

      <InsertDialog
        open={showDialog}
        setShowDialog={setShowDialog}
        items={items?? []}
      />

      <ItemDialog
        open={showDetailDialog}
        setShowDialog={setShowDetailDialog}
        item={data}
      />
    </>
  );
}